package com.test.clyq.daoImpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.dao.DataAccessException;

import com.test.clyq.dao.CommentDao;
import com.test.clyq.entity.Comment;
import com.test.clyq.entity.Users;
import com.test.dao.hibernate.BaseDaoHibernate;
import com.test.util.FormatExceptionStack;
import com.test.util.Pagination;
import com.test.util.SessionFactoryUtil;

/**
 * CommentDAOImp. <br>
 * 评论管理.
 * <p>
 * Copyright: Copyright (c) 2010-3-17 下午04:30:46
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: suncg@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */
@SuppressWarnings("unchecked")
public class CommentDaoHibernate extends BaseDaoHibernate implements CommentDao {

	/**
	 * 删除评论
	 * 
	 * @param id
	 * @param user
	 */
	public boolean deleteComment(Long id, Users user) {
		this.log.info("根据评论ID删除评论start");
		try {

			if (user != null) {
				removeItem(Comment.class, id, user);
				this.log.debug("删除评论成功");
				this.log.info("根据评论ID删除评论end");
				return true;
			} else {
				this.log.debug("删除评论失败");
				return false;
			}
		} catch (DataAccessException e) {
			this.log.error("[Comment]deleteComment发生错误！\n"
					+ FormatExceptionStack.formatException(e));
			return false;
		}
	}

	/**
	 * 通过分页获取全部评论
	 * 
	 * @param pagination
	 * @return
	 */
	public List<Comment> getAllCommentByPage(Pagination pagination) {
		this.log.info("获得评论列表start");
		String sql = "";
		// if (type == 0) {// 图片
		// sql = "from Comment as c where c.downloadFile.id = " + categoryId +
		// " order by c.commentTime desc";
		// } else {// 文章
		sql = "from Comment as c order by c.commentStatus, c.commentTime desc";
		// }
		SessionFactory sessionFactory = getHibernateTemplate()
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*) " + sql);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination
						.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得评论列表end");
				return list;
			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<Comment>();
			}
		} catch (DataAccessException e) {
			this.log.error("[Comment]getCommentByPage发生错误！\n"
					+ FormatExceptionStack.formatException(e));
			return new ArrayList<Comment>();
		} finally {
			SessionFactoryUtil.isClose(session);
		}

	}

	/**
	 * 通过分页获取全部评论
	 * 
	 * @param pagination
	 * @return
	 */
	public List<Comment> getAllCommentTitleByPage(Pagination pagination) {
		this.log.info("获得评论列表start");
		String sql = "";

		sql = "select c.COMMENT_ID,c.COMMENT_CONTENT,c.MOBILE,c.COMMENT_STATUS,c.COMMENT_TIME,e.ENTITY_NAME from T_COMMENT c,T_ENTITY_ITEM e where c.ENTITY_ITEM_COMMENT_ID = e.ENTITY_ITEM_ID order by c.COMMENT_STATUS, c.COMMENT_TIME desc";

		SessionFactory sessionFactory = getHibernateTemplate()
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createSQLQuery("select count(*) from (" + sql
					+ ")");
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(Integer.parseInt(listCount.get(0)
						.toString())); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createSQLQuery(sql.toString());
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());

			List comList = new ArrayList<Comment>();
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得评论列表end");
				for (int i = 0; i < list.size(); i++) {
					Comment com = new Comment();
					Object[] object = (Object[]) list.get(i);

					java.math.BigDecimal mmBigDecimal = (java.math.BigDecimal) object[0];
					int id = mmBigDecimal.intValue();

					java.math.BigDecimal mmBigDecimalStatus = (java.math.BigDecimal) object[3];
					int status = mmBigDecimalStatus.intValue();

					java.math.BigDecimal mmBigDecimalTime = (java.math.BigDecimal) object[4];
					Long time = mmBigDecimalTime.longValue();

					com.setCommentId(Long.valueOf(id));
					com.setCommentContent((String) object[1]);
					com.setMobile((String) object[2]);
					com.setCommentStatus(status);
					com.setCommentTime(time);
					com.setEntityName((String) object[5]);

					comList.add(com);
				}
				return comList;
			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<Comment>();
			}
		} catch (DataAccessException e) {
			this.log.error("[Comment]getCommentByPage发生错误！\n"
					+ FormatExceptionStack.formatException(e));
			return new ArrayList<Comment>();
		} finally {
			SessionFactoryUtil.isClose(session);
		}

	}

	/**
	 * 通过分页获取评论
	 * 
	 * @param pagination
	 * @return
	 */

	public List<Comment> getCommentByPage(Pagination pagination,
			Long categoryId, Integer type) {
		this.log.info("获得评论列表start");
		String sql = "";
		// if (type == 0) {// 图片
		// sql = "from Comment as c where c.downloadFile.id = " + categoryId +
		// " order by c.commentTime desc";
		// } else {// 文章
		sql = "from Comment as c where c.entityItemCommentId = " + categoryId
				+ " order by c.commentTime desc";
		// }
		SessionFactory sessionFactory = getHibernateTemplate()
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*) " + sql);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination
						.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得评论列表end");
				return list;
			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<Comment>();
			}
		} catch (DataAccessException e) {
			this.log.error("[Comment]getCommentByPage发生错误！\n"
					+ FormatExceptionStack.formatException(e));
			return new ArrayList<Comment>();
		} finally {
			SessionFactoryUtil.isClose(session);
		}

	}

	/**
	 * 获取所有评论
	 * 
	 * @return
	 */
	public List<Comment> getComments(Long categoryId) {
		this.log.info("获得现在文件列表start");
		SessionFactory sessionFactory = getHibernateTemplate()
				.getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session
					.createQuery("from Comment as file where category.categoryId = "
							+ categoryId
							+ " order by file.isTip desc, file.weight desc, file.uploadTime desc");
			List list = query.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得评论列表end");
				return list;
			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<Comment>();
			}
		} catch (DataAccessException e) {
			this.log.error("[Comment]getComments发生错误！\n"
					+ FormatExceptionStack.formatException(e));
			return new ArrayList<Comment>();
		} finally {
			SessionFactoryUtil.isClose(session);
		}

	}

	/**
	 * 获取一个评论
	 */
	public Comment getOneComment(Long id) {
		this.log.info("根据评论ID获得评论start");
		try {
			Comment file = (Comment) getItem(Comment.class, id);
			if (file != null) {
				this.log.info("根据评论ID获得评论end");
				return file;
			} else {
				this.log.info("根据评论ID获得评论end");
				return new Comment();
			}

		} catch (DataAccessException e) {
			this.log.error("[Comment]getOneComment发生错误！\n"
					+ FormatExceptionStack.formatException(e));
			return new Comment();
		}
	}

	/**
	 * 修改或保存评论
	 * 
	 * @param id
	 * @param user
	 */
	public void saveOrUpdateComment(Comment file, Users user) {
		this.log.info("保存或更新评论start");
		try {
			saveOrUpdateItem(file, user);
			this.log.debug("保存或更新评论成功");
			this.log.info("保存或更新评论end");
		} catch (DataAccessException e) {
			this.log.error("[Comment]updateComment发生错误！\n"
					+ FormatExceptionStack.formatException(e));
		}
	}
}
